package com.mifengs.mall.services;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;

import com.mifengs.commonbase.util.LogUtil;
import com.mifengs.mall.Constant;
import com.mifengs.mall.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by lihaoqi on 2017/8/28.
 */

public class DownloadService extends Service implements DownLoadListener {

    private static DownloadService instance;
    private static final String TAG = "DownloadService";
    private static final int NOTIFICATION_FLAG = 1;
    private Notification.Builder builder;
    private NotificationManager manager;
    private int oldProgress;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String fileUrl = intent.getStringExtra("AppUpdateInfo");
      //  String fileUrl = "https://www.mifengs.com/mifengs_m/resources/downloadApp/mifengs.apk";
        DownloadAsyncTask downloadAsyncTask = new DownloadAsyncTask(fileUrl);
        downloadAsyncTask.setDownLoadListener(this);
        downloadAsyncTask.execute();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void updateProgress(int progress) {
        LogUtil.i(TAG,progress+"");
        if(progress!=oldProgress){
            builder.setContentText(progress+"%");
            builder.setProgress(100,progress,false);
            manager.notify(NOTIFICATION_FLAG, builder.build());
            oldProgress = progress;
        }
    }

    @Override
    public void finish() {
        if(builder!=null){
            LogUtil.i(TAG,"finish");
            builder.setProgress(0,0,false).setOngoing(false);
            builder.setContentTitle("下载完成");
            manager.notify(NOTIFICATION_FLAG, builder.build());
            install();
            this.stopSelf();
        }else{
            this.stopSelf();
        }
    }

    private void install() {
        File file= new File(Constant.AppPath, "mfsc.apk");
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.N){
            Uri apkUri = FileProvider.getUriForFile(this, "com.mifengs.mall.provider", file);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            // 由于没有在Activity环境下启动Activity,设置下面的标签
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            startActivity(intent);
        }else{
            Intent intent =  new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }

    @Override
    public void start() {
        showNotification();
    }

    private void showNotification() {
        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.app_ic_launcher)
                .setTicker("下载中")
                .setOngoing(true).setContentTitle("下载中")
                .setContentText("0%")
                .setProgress(100,0,false);


        manager.notify(NOTIFICATION_FLAG, builder.build());
    }

    class DownloadAsyncTask extends AsyncTask<String,String,String> {

        private String fileUrl;
        private static final String TAG = "DownloadAsyncTask";
        private DownLoadListener mDownLoadListener;

        public DownloadAsyncTask(String fileUrl) {
            this.fileUrl = fileUrl;
        }

        public void setDownLoadListener(DownLoadListener mDownLoadListener){
            this.mDownLoadListener = mDownLoadListener;
        }

        @Override
        protected String doInBackground(String... params) {
            return downloadApp();
        }


        private String downloadApp() {
            try {
                //连接地址
                URL u = new URL(fileUrl);
                LogUtil.i(TAG, u.toString());
                HttpURLConnection c = (HttpURLConnection) u.openConnection();
                c.setRequestMethod("GET");

                c.connect();

                //计算文件长度
                int lenghtOfFile = c.getContentLength();

                File fd = new File(Constant.AppPath);
                if((!fd.exists())&&(!fd.isDirectory())){
                    fd.mkdir();
                }

                FileOutputStream fos = new FileOutputStream(new File(Constant.AppPath, "mfsc.apk"));

                InputStream in = c.getInputStream();
                mDownLoadListener.start();
                //下载的代码
                byte[] buffer = new byte[1024];
                int len1 = 0;
                long total = 0;

                while ((len1 = in.read(buffer)) > 0) {
                    total += len1; //total = total + len1
                    publishProgress("" + (int)((total*100)/lenghtOfFile));
                    fos.write(buffer, 0, len1);
                }
                fos.close();
            } catch (Exception e) {
                LogUtil.e(TAG,e.getMessage());
            }

            return null;
        }

        @Override
        protected void onProgressUpdate(String... value) {
            int progress = Integer.parseInt(value[0]);
            mDownLoadListener.updateProgress(progress);
        }

        @Override
        protected void onPostExecute(String s) {
            mDownLoadListener.finish();
        }

    }

}
